<?php
include_once 'models/Cell.php';
include_once 'models/Event.php';
include_once 'models/App.php';
include_once 'models/Menu.php';
include_once 'models/Subsite.php';

	//connects to mysql database using mysqli
	class DBConnect
	{
		//db settings:
		const HOST = '127.0.0.1';
		const USER = 'appviewer';
		const PASSWORD = '1234';
		const DATABASE = 'app_tool';
		//end db settings
	
		private static $instance;
		
		private $connectionOpen;
		private $mysqli;
		
		
		private function __construct() {
			//init vars
			$connectionOpen = false;
		}
		
		public static function getInstance() {
			if(!isset(DBConnect::$instance) || empty(DBConnect::$instance)) {
				DBConnect::$instance = new DBConnect();
			}
			return DBConnect::$instance;
		}
		
		public function connect() {
			$this->mysqli = new mysqli(self::HOST, self::USER, self::PASSWORD, self::DATABASE);
			if($this->mysqli->connect_errno) {
				return false;
			}
			else {
				$this->connectionOpen = true;
				return true;
			}
		}
		
		public function isConnected() {
			return $connectionOpen;
		}
		
		public function closeConnection() {
			$this->mysqli->close();
		}
		
		//************************** QUERY METHODS ******************* 
		
		//Returns an associative array with the (first) result of the select-query
		private function selectQuery($query) {
			if(! $this->connectionOpen) {
				//TODO: Handle query on closed connection better
				return array("error" => "Connection not open in DBConnect!");
			}
			else {
				$result = $this->mysqli->query($query);
				return $result->fetch_assoc();
			}
		}
		
		//returns an array of associative arrays with the results of the select-query
		private function selectAll($query) {
			if(! $this->connectionOpen) {
				//TODO: Handle query on closed connection better
				return array("error" => "Connection not open in DBConnect!");
			}
			else {
				$dbresult = $this->mysqli->query($query);
				
				$allResults = array();
				
				//while there are still results to get...
				while($result = $dbresult->fetch_assoc()) {
					//.. add these to $allResults
					$allResults[] = $result;
				}
				
				return $allResults;
			}
		}
		
		/******************* DATA TO DATABASE *******************/
		public function saveSubsite($html) {
			if(! $this->connectionOpen) {
				return array("error" => "Connection not open in DBConnect!");
			}
			else {
				//insert subsite:
				$this->mysqli->query('INSERT INTO AppSubsite (`html`) VALUES ("'.$html.'")');
				
				//resulting id
				$id = $this->mysqli->insert_id;
				return $id;
			}
		}
		
		//returns error array on closed connection, mysqli error.
		public function saveCell($eventID, $btnText, $subsiteID, $posX, $posY) {	
			if(! $this->connectionOpen) {
				return array("error" => "Connection not open in DBConnect!");
			}
			else {
				//insert subsite:
				$this->mysqli->query('INSERT INTO AppMenu (`EventID`, `ButtonText`, `SubsiteID`, `positionX`, `positionY`) VALUES ('.$eventID.',"'.$btnText.'",'.$subsiteID.','.$posX.','.$posY.')');
				
				//return $this->mysqli->error; //<--- for testing
				return 'success'; //<-- because why not
			}
		}		
		
		//************ DATABASE TO OBJECT METHODS ***********
		
		public function fetchEvent($eventID) {
			$dbevent = $this->selectQuery('SELECT ID, ShortID, Name, Description, StartTime, Banner FROM Event WHERE ID = '.$eventID);
			
			if(isset($dbevent["error"])) {
				//TODO: handle error better
				return $dbevent;	//<-- a var_dump can explain what went wrong
			}
			else {			
				
				return $this->buildEvent($dbevent);
			}
		}
		
		public function fetchMenu($eventID) {
			$dbmenu = $this->selectAll('SELECT ID, EventID, ButtonText, SubsiteID, PositionX, PositionY FROM AppMenu WHERE EventID = '.$eventID);
			if(isset($dbmenu["error"])) {
				//TODO: handle error better
				return $dbmenu; //<-- a var_dump can explain what went wrong
			}
			else {
				return $this->buildMenu($dbmenu);
			}
		}
		
		public function fetchSubsite($subsiteID) {
			$dbsubsite = $this->selectQuery('SELECT ID, HTML FROM AppSubsite WHERE ID = '.$subsiteID);
			if(isset($dbsubsite["error"])) {
				//TODO: handle error better
				return $dbsubsite; //<-- a var_dump can explain what went wrong
			}
			else {
				return $this->buildSubsite($dbsubsite);
			}
		}
		
		private function buildEvent($dbevent) 
		{
			$id = $dbevent['ID'];
			$short_id = $dbevent['ShortID'];
			$name = $dbevent['Name'];
			$description = $dbevent['Description'];
			$startTime = $dbevent['StartTime'];
			$banner = $dbevent['Banner'];
			
			return new Event($id, $short_id, $name, $description, $startTime, $banner);
		}
		
		private function buildMenu($dbCellArr) {
			$menu = new Menu();
				
			//populate the menu with cells:
			foreach($dbCellArr as $dbcell) {
				$cell = $this->buildCell($dbcell);
				$menu->addCell($cell, $dbcell['PositionX'], $dbcell['PositionY']);
			}
			
			return $menu;
		}
		
		private function buildCell($dbcell) {
			//a cell needs a subsite....
			$subsite = $this->fetchSubsite($dbcell['SubsiteID']);
			return new Cell($dbcell['ButtonText'], $subsite);
		}
		
		private function buildSubsite($dbsubsite) {
			return new Subsite($dbsubsite['ID'], $dbsubsite['HTML']);
		}
	}
?>